﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>单元格自动计算 </title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <link href="../demo.css" rel="stylesheet" type="text/css" />

    
    <script src="../../scripts/boot.js" type="text/javascript"></script> 
    

</head>
<body>
    <h1>单元格自动计算</h1>
    

    <div id="datagrid1" class="mini-datagrid" style="width:800px;height:280px;"
        idField="id" allowCellEdit="true" allowCellSelect="true"  showFooter="false" 
        url="../data/grid2.txt"
        ondrawcell="onDrawCell" oncellcommitedit="onCellCommitEdit"
        showSummaryRow="true" ondrawsummarycell="onDrawSummaryCell"
    >
        <div property="columns">       
            <div field="price" width="120" headerAlign="center" allowSort="true">单价
                <input property="editor" class="mini-textbox" style="width:100%;" vtype="float"/>
            </div>    
            <div field="quantity" width="120" headerAlign="center" allowSort="true">数量
                <input property="editor" class="mini-textbox" style="width:100%;" vtype="int"/>
            </div>
            <div field="total" width="120" headerAlign="center" allowSort="true">总计</div>
        </div>
    </div>    
    <script type="text/javascript">
        mini.parse();

        var grid = mini.get("datagrid1");
        grid.load();

        //////////////////////////////////////////
        //提交单元格编辑数据前激发
        function onCellCommitEdit(e) {
            var editor = e.editor;
            
            editor.validate();
            if (editor.isValid() == false) {
                alert(editor.getErrorText());
                e.cancel = true;
            }
        }

        function onDrawCell(e) {
            var record = e.record;

            if (e.field == "total") {
                var price = record.price;
                var quantity = record.quantity;
                e.cellHtml = price * quantity;
            }

        }

        function onDrawSummaryCell(e) {
            var result = e.result;
            var grid = e.sender;
            var rows = e.data;
            
            if (e.field == "total") {
                var total = 0;
                for (var i = 0, l = rows.length; i < l; i++) {
                    var row = rows[i];
                    var t = row.price * row.quantity;
                    if (isNaN(t)) continue;
                    total += t;
                }

                e.cellHtml = "总计: " + total;
            }
        }

    </script>

    <div class="description">
        <h3>Description</h3>
        <p>“总计”列的值由“单价”和“数量”相乘而来。</p>
    </div>
</body>
</html>